<template>
  <nav class="navbar">
    <div class="container navbar-container">
      <div class="navbar-brand">
        <router-link to="/" class="logo">
          <span class="logo-text">CarbonSpark</span>
        </router-link>
        <span class="slogan">让低碳生活更有价值</span>
      </div>

      <div class="navbar-menu">
        <div class="navbar-links">
          <router-link to="/" class="nav-link" exact>首页</router-link>
          <router-link to="/community" class="nav-link">社区</router-link>
          <router-link to="/challenges" class="nav-link">挑战</router-link>
          <!-- 暂时隐藏环保知识和积分商城链接 -->
          <!-- <router-link to="/knowledge" class="nav-link">环保知识</router-link> -->
          <!-- <router-link to="/points" class="nav-link">积分商城</router-link> -->
          <router-link to="/about" class="nav-link">关于我们</router-link>
          <router-link to="/admin" class="nav-link admin-link">管理后台</router-link>
        </div>

        <!-- 根据登录状态显示不同的导航元素 -->
        <div v-if="isLoggedIn" class="user-profile-section">
          <div class="user-avatar-wrapper" @click="toggleDropdown" ref="avatarRef">
            <div class="user-avatar">
              <!-- 显示加载状态 -->
              <div v-if="loading" class="loading-avatar">
                <div class="spinner"></div>
              </div>
              <!-- 如果有头像，显示头像 -->
              <img v-else-if="userInfo && userInfo.avatar" :src="userInfo.avatar" class="avatar-img" alt="用户头像" />
              <!-- 否则显示渐变色默认头像 -->
              <div v-else class="gradient-avatar" :style="{ background: generateGradient() }">
                {{ userInitials }}
              </div>
            </div>
          </div>
          
          <!-- 用户下拉菜单 -->
          <div class="dropdown-menu" v-show="showDropdown">
            <div class="dropdown-header">
              <div v-if="loading" class="loading-text">正在加载用户信息...</div>
              <div v-else-if="error" class="error-text">{{ error }}</div>
              <div v-else class="dropdown-username">{{ userInfo ? userInfo.nickName || userInfo.userName : '用户' }}</div>
            </div>
            <router-link to="/profile" class="dropdown-item">个人资料</router-link>
            <router-link to="/settings" class="dropdown-item">设置</router-link>
            <div class="dropdown-divider"></div>
            <div class="dropdown-item" @click="handleLogout">退出登录</div>
          </div>
        </div>
        <div v-else class="navbar-buttons">
          <router-link to="/login" class="btn btn-outline">登录</router-link>
          <router-link to="/register" class="btn btn-primary">注册</router-link>
        </div>
      </div>
    </div>
  </nav>
</template>

<script>
import { isLoggedIn, getUserInfo, logout as authLogout, getCurrentUserName } from '@/utils/auth'
import { getCurrentUserInfo } from '@/api/auth'

export default {
  name: 'NavbarComponent',
  data() {
    return {
      showDropdown: false,
      userInfo: null,
      loading: false,
      error: null,
      loggedIn: false, // 添加本地登录状态跟踪
      userInfoNeedsRefresh: false // 添加标记表示用户信息需要强制刷新
    }
  },
  computed: {
    isLoggedIn() {
      return this.loggedIn || isLoggedIn() // 优先使用本地状态
    },
    userInitials() {
      if (!this.userInfo) return '用'
      
      const name = this.userInfo.nickName || this.userInfo.userName || ''
      if (!name) return '用'
      
      // 如果是中文名，取第一个字
      if (/[\u4e00-\u9fa5]/.test(name)) {
        return name.charAt(0)
      }
      
      // 如果是英文名，取首字母
      return name.charAt(0).toUpperCase()
    }
  },
  created() {
    // 检查登录状态
    this.checkLoginStatus()
    
    // 监听登录成功事件
    this.$root.$on('login-success', () => {
      this.loggedIn = true
      
      // 登录后获取本地存储的用户信息，但不主动请求API
      this.userInfo = getUserInfo()
    })
    
    // 监听登出事件
    this.$root.$on('logout', () => {
      this.loggedIn = false
      this.userInfo = null
    })
    
    // 监听用户信息更新事件
    this.$root.$on('user-info-updated', () => {
      // 用户修改了信息后，我们不立即刷新，而是在下次访问profile页面时强制刷新
      this.userInfoNeedsRefresh = true
    })
    
    // 监听路由变化，只在进入profile页面时请求用户信息
    this.$router.beforeEach((to, from, next) => {
      if (to.path === '/profile' && this.isLoggedIn) {
        this.fetchCurrentUserInfo(this.userInfoNeedsRefresh)
        this.userInfoNeedsRefresh = false // 重置状态
      }
      next()
    })
    
    // 添加点击页面其他区域关闭下拉菜单的事件监听
    document.addEventListener('click', this.handleOutsideClick)
  },
  mounted() {
    // 在组件挂载后再次检查登录状态，确保状态正确
    setTimeout(() => {
      this.checkLoginStatus()
      
      // 如果是登录状态但没有用户信息，尝试从localStorage获取
      if (this.isLoggedIn && !this.userInfo) {
        this.userInfo = getUserInfo()
      }
    }, 100)
  },
  beforeDestroy() {
    // 移除事件监听
    document.removeEventListener('click', this.handleOutsideClick)
    // 移除全局事件监听
    this.$root.$off('login-success')
    this.$root.$off('logout')
    this.$root.$off('user-info-updated')
  },
  methods: {
    // 检查登录状态并获取用户信息
    checkLoginStatus() {
      const loginState = isLoggedIn()
      
      if (loginState) {
        this.loggedIn = true
        // 首先获取本地存储的用户信息
        this.userInfo = getUserInfo()
      } else {
        this.loggedIn = false
        this.userInfo = null
      }
    },
    // 使用指定用户名调用API
    async fetchUserInfoWithName(userName, forceRefresh = false) {
      this.loading = true
      this.error = null
      
      try {
        const response = await getCurrentUserInfo(userName, forceRefresh)
        
        if (response.success && response.data) {
          // 更新用户信息到组件和本地存储
          this.userInfo = response.data
          // 同时更新本地存储的用户信息
          import('@/utils/auth').then(module => module.setUserInfo(response.data))
        } else {
          this.error = response.message || '获取用户信息失败'
        }
      } catch (error) {
        this.error = error.message || '获取用户信息出错'
      } finally {
        this.loading = false
      }
    },
    async fetchCurrentUserInfo(forceRefresh = true) {
      // 如果没有登录信息，直接返回
      if (!this.isLoggedIn) {
        return
      }

      // 获取用户名
      const localUserInfo = getUserInfo()
      
      let userName = '';
      
      // 优先使用内存中的用户名
      userName = getCurrentUserName()
      // 如果内存中没有，使用本地存储的用户名
      if (!userName && localUserInfo && localUserInfo.userName) {
        userName = localUserInfo.userName
      } 
      // 如果都没有，尝试使用记住的用户名
      else if (!userName) {
        userName = localStorage.getItem('rememberedUsername')
      }
      
      if (!userName) {
        return
      }

      // 使用共通方法发送请求，传递强制刷新参数
      this.fetchUserInfoWithName(userName, forceRefresh)
    },
    toggleDropdown() {
      this.showDropdown = !this.showDropdown
      
      // 不要在下拉菜单打开时请求用户信息 - 除非在profile页面
      if (this.showDropdown && this.isLoggedIn && (!this.userInfo || !this.userInfo.nickName) && 
          this.$route.path === '/profile') {
        this.fetchCurrentUserInfo()
      }
    },
    handleOutsideClick(event) {
      // 如果点击的不是头像也不是下拉菜单内的元素，则关闭下拉菜单
      if (this.$refs.avatarRef && !this.$refs.avatarRef.contains(event.target) && 
          this.showDropdown && !event.target.closest('.dropdown-menu')) {
        this.showDropdown = false
      }
    },
    generateGradient() {
      // 根据用户名生成一个固定的渐变色
      let hash = 0
      const name = this.userInfo ? (this.userInfo.userName || '') : ''
      
      for (let i = 0; i < name.length; i++) {
        hash = name.charCodeAt(i) + ((hash << 5) - hash)
      }
      
      // 确保哈希值为正
      hash = Math.abs(hash)
      
      // 生成两个颜色
      const hue1 = hash % 360
      const hue2 = (hash * 7) % 360
      
      return `linear-gradient(135deg, hsl(${hue1}, 70%, 60%), hsl(${hue2}, 70%, 60%))`
    },
    async handleLogout() {
      try {
        // 获取用户名 - 优先使用内存中的变量
        
        // 从内存中获取用户名
        let userName = getCurrentUserName();
        
        // 如果内存中没有，尝试从其他来源获取
        if (!userName) {
          // 1. 从本地用户信息获取
          const localUserInfo = getUserInfo();
          
          // 2. 从localStorage尝试获取备用用户名
          const savedUserName = localStorage.getItem('rememberedUsername');
          
          // 3. 使用任一可用的用户名
          userName = localUserInfo?.userName || savedUserName;
        }
        
        if (!userName) {
          // 即使没有用户名，也执行前端登出操作
          authLogout(); 
          this.showDropdown = false;
          this.loggedIn = false;
          this.userInfo = null;
          this.$root.$emit('logout');
          window.location.href = window.location.origin + '/';
          return;
        }
        
        // 调用登出API
        try {
          const authModule = await import('@/api/auth');
          
          // 调用登出API，不需要使用响应结果
          await authModule.logout(userName);
          
          // 即使API响应为失败也继续前端登出流程
        } catch (apiError) {
          // 即使API调用失败也继续前端登出
        }
        
        // 无论API调用成功与否，都执行前端登出操作
        
        // 清除本地存储
        authLogout(); // 这里会调用clearCurrentUserName()
        
        // 关闭下拉菜单
        this.showDropdown = false;
        
        // 更新本地状态
        this.loggedIn = false;
        this.userInfo = null;
        
        // 触发登出事件
        this.$root.$emit('logout');
        
        // 使用window.location刷新页面
        const baseUrl = window.location.origin;
        window.location.href = baseUrl + '/';
        
      } catch (error) {
        // 尝试简单登出
        authLogout();
        alert('登出过程中发生错误: ' + error.message);
        // 尝试重新加载页面
        window.location.reload();
      }
    }
  }
}
</script>

<style scoped>
.navbar {
  background-color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  height: 70px;
}

.navbar-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 70px;
  padding: 0 20px;
  margin: 0 auto;
  max-width: 1200px;
}

.navbar-brand {
  display: flex;
  align-items: center;
}

.logo {
  text-decoration: none;
  display: flex;
  align-items: center;
}

.logo-text {
  font-size: 24px;
  font-weight: bold;
  color: #4CAF50;
  margin-right: 10px;
}

.slogan {
  font-size: 14px;
  color: #777;
  margin-left: 10px;
}

.navbar-menu {
  display: flex;
  align-items: center;
}

.navbar-links {
  display: flex;
  margin-right: 20px;
}

.nav-link {
  text-decoration: none;
  color: #333;
  font-weight: 500;
  padding: 8px 16px;
  border-radius: 4px;
  transition: background-color 0.3s, color 0.3s;
}

.nav-link:hover,
.nav-link.router-link-active {
  color: #4CAF50;
  background-color: rgba(76, 175, 80, 0.1);
}

.navbar-buttons {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
  text-decoration: none;
  transition: background-color 0.3s, color 0.3s;
}

.btn-outline {
  border: 1px solid #4CAF50;
  color: #4CAF50;
  background-color: transparent;
}

.btn-outline:hover {
  background-color: rgba(76, 175, 80, 0.1);
}

.btn-primary {
  background-color: #4CAF50;
  color: white;
  border: none;
}

.btn-primary:hover {
  background-color: #3d8b40;
}

/* 用户头像和下拉菜单 */
.user-profile-section {
  position: relative;
}

.user-avatar-wrapper {
  cursor: pointer;
  padding: 5px;
  border-radius: 50%;
  background-color: rgba(76, 175, 80, 0.1);
  display: inline-block;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.loading-avatar {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.spinner {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(76, 175, 80, 0.3);
  border-radius: 50%;
  border-top: 2px solid #4CAF50;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.gradient-avatar {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-weight: bold;
  font-size: 18px;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 10px;
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  width: 180px;
  z-index: 10;
}

.dropdown-header {
  padding: 10px 16px;
  border-bottom: 1px solid #eee;
}

.dropdown-username {
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.loading-text {
  font-size: 13px;
  color: #777;
  text-align: center;
}

.error-text {
  font-size: 13px;
  color: #ff4d4f;
  text-align: center;
}

.dropdown-item {
  padding: 10px 16px;
  color: #333;
  display: block;
  text-decoration: none;
  transition: background-color 0.3s;
  cursor: pointer;
}

.dropdown-item:hover {
  background-color: #f5f5f5;
  color: #4CAF50;
}

.dropdown-divider {
  height: 1px;
  background-color: #eee;
  margin: 5px 0;
}

.admin-link {
  color: #ff9800;
  font-weight: bold;
}

.admin-link:hover,
.admin-link.router-link-active {
  color: #ff5722;
  background-color: rgba(255, 152, 0, 0.1);
}

@media (max-width: 768px) {
  .navbar-links {
    display: none;
  }
  
  .slogan {
    display: none;
  }
}
</style> 